import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import Feature from 'ol/Feature';
import { LineString, Point } from 'ol/geom';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { Style, Icon, Text, Fill, Stroke, Circle } from 'ol/style';
import { fromLonLat } from 'ol/proj';
import { GeoJSON } from "ol/format";
import { mainInterval } from "../../config";

interface MoveData {
    time: number; // 时间戳
    coordinates: [number, number]; // 坐标 [longitude, latitude]
    name: string; // 模型名称
    heading: number
}

export default class Playback {
    private map: Map; // 地图对象
    private targetLayer: VectorLayer; // 目标图层
    private moveData: MoveData[]; // 移动数据
    private currentIndex: number; // 当前索引
    private interval: any; // 定时器
    private targetFeature: Feature; // 目标要素
    private playbackSpeed: number; // 播放速度
    private lastUpdate: number; // 上次更新时间
    private trajectoryLayerPointPoint: VectorLayer; // 轨迹图层 点
    private trajectoryLayerPointLine: VectorLayer; // 轨迹图层 点
    private modelName: string;
    public isTracked: boolean = false
    private coordinates;
    public callFunc: Function
    public layer_mgr: any
    private startTime
    private loop:boolean = true;
    constructor(map: Map, callFunc: Function, layer_mgr: any) {
        this.map = map;
        this.callFunc = callFunc
        this.layer_mgr = layer_mgr

    }
    public initCallPlayData(moveData: MoveData[], name: string) {
        this.modelName = name
        this.moveData = moveData.filter((_, index) => index % 50 === 0);
        this.currentIndex = 0;
        this.playbackSpeed = 1; // 默认播放速度

        // 初始化目标图层
        this.targetLayer = new VectorLayer({
            source: new VectorSource(),
            zIndex: 10
        });

        // this.map.addLayer(this.targetLayer);



        // 创建目标要素
        this.targetFeature = new Feature({
            geometry: new Point(fromLonLat(moveData[0].coordinates)),
        });

        this.updateFeatureStyle(moveData[0].name, moveData[0].heading); // 更新样式

        this.targetLayer.getSource().addFeature(this.targetFeature);
        this.lastUpdate = Date.now();
        // 加载轨迹点

        //Point,LineString
        const sourcePoint = this.convertToGeoJSON(this.moveData, 'Point')
        //加载轨迹点

        this.trajectoryLayerPointPoint = new VectorLayer({
            zIndex: 10,
            source: sourcePoint,
            style: new Style({
                image: new Circle({
                    radius: 3, // 点的半径
                    fill: new Fill({ color: "#fff" }), // 内部填充颜色
                    stroke: new Stroke({ color: 'rgba(0, 191, 255, 1)', width: 1 }) // 边框颜色
                }),
            })
        })

        //   this.map.addLayer(this.trajectoryLayerPointPoint)
        //加载轨迹点
        //Point,LineString
        const sourceLine = this.convertToGeoJSON(this.moveData, 'LineString')
        this.trajectoryLayerPointLine = new VectorLayer({
            zIndex: 9,
            source: sourceLine,
            style: new Style({
                stroke: new Stroke({
                    color: 'rgba(0, 0, 255, 1)',
                    width: 4,
                }),
            })
        })
        return [{ name: this.modelName + "_Line", data: this.trajectoryLayerPointLine }, { name: this.modelName + "_Point", data: this.trajectoryLayerPointPoint }, { name: this.modelName + "_Model", data: this.targetLayer }]

    }
    // 更新要素样式，包括文本
    private updateFeatureStyle(name: string, heading: number) {
        this.targetFeature.setStyle(new Style({
            image: new Icon({
                src: "/Image/飞机.png", // 目标图标路径
                scale: 1,
                rotation: (heading * Math.PI) / 180,
                anchor: [0.5, 0.5],
            }),
            text: new Text({
                text: this.modelName,
                scale: 1.5,
                offsetY: -35, // 文本偏移
                fill: new Fill({ color: '#FFF' }),
                stroke: new Stroke({
                    color: '#000000',
                    width: 2,
                }),
                backgroundFill: new Fill({ // 背景颜色  
                    color: 'rgba(0, 0, 0, 0.5)',
                }),
                padding: [5, 5, 5, 5], // 背景填充边距  
            }),
        }));
    }

    // 开始回放
    public startPlayback() {
        // debugger
        if (this.interval) return;
        this.startTime = this.moveData[0].time

        this.interval = setInterval(() => {
            const now = Date.now();
            const deltaTime = (now - this.lastUpdate) / 1000 * this.playbackSpeed; // 计算经过的时间
            this.lastUpdate = now;
            // debugger
            if (this.currentIndex < this.moveData.length - 1) {
                const currentData = this.moveData[this.currentIndex];
                const nextData = this.moveData[this.currentIndex + 1];

                // 使用 deltaTime 进行插值处理
                const interpolatedCoords = this.interpolate(currentData, nextData, deltaTime);
                this.targetFeature.setGeometry(new Point(fromLonLat(interpolatedCoords)));

                if (this.isTracked) {
                    this.map.getView().setCenter(fromLonLat(interpolatedCoords));
                }
                // 更新图标名称
                this.updateFeatureStyle(currentData.name, currentData.heading);
                this.updatePosition(currentData)
                this.updateRadar(currentData)
                // 检查是否需要移动到下一个数据点
                if (now >= nextData.time) {
                    this.currentIndex++;
                }
            } else {
                this.reset();
            }
        }, mainInterval); // 每100毫秒刷新一次，增加平滑效果
    }

    // 停止回放
    public stopPlayback() {
        // if(this.loop){
        //     this.startPlayback()
        //     return
        // }
        if (this.interval) {
            clearInterval(this.interval);
            this.interval = null;
        }
    }

    public reset(){
        //  debugger
         this.trajectoryLayerPointLine.getSource().clear()
         this.trajectoryLayerPointLine.getSource().clear()
        //  this.targetLayer.getSource().clear()
         this.coordinates = []
         clearInterval(this.interval)
         this.interval = null;
         this.currentIndex = 0
         this.startPlayback()
    }

    // 插值处理
    private interpolate(current: MoveData, next: MoveData, deltaTime: number): [number, number] {
        const totalDuration = (next.time - current.time); // 转换为毫秒
        const progress = Math.min(deltaTime / totalDuration, 1); // 计算当前进度

        const lat = current.coordinates[1] + (next.coordinates[1] - current.coordinates[1]) * progress;
        const lon = current.coordinates[0] + (next.coordinates[0] - current.coordinates[0]) * progress;
        return [lon, lat];
    }

    // 设置播放速度
    public setPlaybackSpeed(speed: number) {
        this.playbackSpeed = speed; // 
        
    }

    // 根据拖动时间轴匹配回放
    public seekTo(time: number) {
        // 找到与当前时间匹配的数据点
        const targetIndex = this.moveData.findIndex(data => data.time >= time);
        if (targetIndex !== -1) {
            this.currentIndex = targetIndex; // 更新当前索引
            this.targetFeature.setGeometry(new Point(fromLonLat(this.moveData[targetIndex].coordinates))); // 更新目标位置
            this.map.getView().setCenter(fromLonLat(this.moveData[targetIndex].coordinates)); // 更新地图中心
            this.updateFeatureStyle(this.moveData[targetIndex].name, this.moveData[targetIndex].heading); // 更新图标名称
        }
    }

    // 加载轨迹
    private loadTrajectory() {
        //Point,LineString
        const sourcePoint = this.convertToGeoJSON(this.moveData, 'Point')
        //加载轨迹点

        this.trajectoryLayerPointPoint = new VectorLayer({
            zIndex: 10,
            source: sourcePoint,
            style: new Style({
                image: new Circle({
                    radius: 3, // 点的半径
                    fill: new Fill({ color: "#fff" }), // 内部填充颜色
                    stroke: new Stroke({ color: 'rgba(0, 191, 255, 1)', width: 1 }) // 边框颜色
                }),
            })
        })

        this.map.addLayer(this.trajectoryLayerPointPoint)
        //加载轨迹点
        //Point,LineString
        const sourceLine = this.convertToGeoJSON(this.moveData, 'LineString')
        this.trajectoryLayerPointLine = new VectorLayer({
            zIndex: 9,
            source: sourceLine,
            style: new Style({
                stroke: new Stroke({
                    color: 'rgba(0, 0, 255, 1)',
                    width: 4,
                }),
            })
        })

        this.map.addLayer(this.trajectoryLayerPointLine)
    }
    convertToGeoJSON(coords, type) {
        // 获取坐标，确保只取一个坐标
        this.coordinates = coords.length > 0 ? [coords[0].coordinates] : []; // 只取第一个坐标

        let geojson;
        if (type === 'Point' && this.coordinates.length > 0) {
            // 生成 GeoJSON 字符串，只有一个 Point 特征
            geojson = {
                type: 'FeatureCollection',
                features: [{
                    type: 'Feature',
                    geometry: {
                        type: "Point",
                        coordinates: this.coordinates[0], // 使用第一个坐标
                    },
                    properties: {
                        // 可以在这里添加属性
                    },
                }]
            };

        } else {
            // 生成 GeoJSON 字符串，只有一个坐标点
            geojson = {
                type: "Feature",
                geometry: {
                    type: "LineString",
                    coordinates: this.coordinates, // 只有一个坐标
                },
                properties: {
                    // 可以在这里添加其他属性
                }
            };
        }


        // 将 GeoJSON 加载到地图
        const vectorSource = new VectorSource({
            features: new GeoJSON().readFeatures(geojson, {
                dataProjection: 'EPSG:4326', // 输入数据的投影
                featureProjection: 'EPSG:3857', // 地图的投影
            }),
        });
        return vectorSource
    }

    public updateRadar(newData) {
        let difference = Math.abs(Math.floor((newData.time - this.startTime) / 1000));
        if (difference >= 6 * 60) {
            this.startTime = newData.time
            // setTimeout(() => {
                this.callFunc()
            // }, 1000);
        

        }
    }

    private updatePosition(newCoords) {
        this.coordinates.push(newCoords.coordinates); // 将新坐标添加到数组中

        // 更新 LineString 特征
        const lineStringFeature = {
            type: "Feature",
            geometry: {
                type: "LineString",
                coordinates: this.coordinates, // 只有一个坐标
            },
            properties: {
                // 可以在这里添加其他属性
            }
        };

        // const geojson = {
        //     type: 'FeatureCollection',
        //     features: this.coordinates.map((coord) => ({
        //         type: 'Feature',
        //         geometry: {
        //             type: "Point",
        //             coordinates: coord,
        //         },
        //         properties: {
        //         },
        //     }))
        // };
        this.trajectoryLayerPointLine.getSource().clear()
        this.trajectoryLayerPointLine.getSource().addFeatures(new GeoJSON().readFeatures(
            lineStringFeature, {
            dataProjection: 'EPSG:4326', // 输入数据的投影
            featureProjection: 'EPSG:3857', // 地图的投影
        }
        ))
        this.trajectoryLayerPointPoint.getSource().clear()
        // this.trajectoryLayerPointPoint.getSource().addFeatures(new GeoJSON().readFeatures(
        //     geojson, {
        //     dataProjection: 'EPSG:4326', // 输入数据的投影
        //     featureProjection: 'EPSG:3857', // 地图的投影
        // }
        // ))
    }

    public clearData() {
        return [this.modelName + "_Model", this.modelName + "_Point", this.modelName + "_Line"]
    }
}
